package com.share.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.share.constants.UserType;
import com.share.mapper.DriverWalletMapper;
import com.share.openfeign.UaaOpenfeign;
import com.share.pojo.domain.Driver;
import com.share.mapper.DriverMapper;
import com.share.pojo.domain.DriverWallet;
import com.share.pojo.domain.LoginVo;
import com.share.result.JSONResult;
import com.share.service.IDriverService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.spring.annotation.datasource.EnableAutoDataSourceProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 * 司机对象 服务实现类
 * </p>
 *
 * @author zcj
 * @since 2025-03-25
 */
@Service
public class DriverServiceImpl extends ServiceImpl<DriverMapper, Driver> implements IDriverService {
    @Autowired
    private DriverWalletMapper driverWalletMapper;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private UaaOpenfeign uaaOpenfeign;

    @Override
//    @GlobalTransactional(name = "driver-wechat-register",rollbackFor = Exception.class)
    public JSONResult register(Driver driver) {
        //根据openId去数据库里面查询
        Driver driver2 = driverMapper.selectOne(new LambdaQueryWrapper<Driver>()
                .eq(Driver::getOpenId,driver.getOpenId()));
        //有|没有
        if(driver2 != null){
            return JSONResult.success();
        }else {
            //保存 司机的初始化信息
            Date date = new Date();
            BigDecimal bigDecimal = new BigDecimal(0);
            Driver driver1 = new Driver();
            driver1.setOpenId(driver.getOpenId());
            driver1.setPhone(driver.getPhone());
            driver1.setCreateTime(date);
            long id = IdUtil.createSnowflake(0L, 0L).nextId();
            driver1.setId(id);
            super.save(driver1);
            //保存 钱包 结算 初始化信息
            DriverWallet driverWallet = new DriverWallet();
            driverWallet.setId(id);
            driverWallet.setAmount(bigDecimal);
            driverWallet.setCreateTime(date);
            driverWallet.setTotalRecharge(bigDecimal);
            driverWallet.setTotalWithdraw(bigDecimal);
            driverWalletMapper.insert(driverWallet);
            //  结算  todo
            //远程调用
            LoginVo loginVo = new LoginVo();
            loginVo.setId(id);
            loginVo.setOpenId(driver.getOpenId());
            loginVo.setPhone(driver.getPhone());
            loginVo.setType(UserType.driver);
            uaaOpenfeign.register(loginVo);
        }
        return JSONResult.success();
    }
}
